<template>
	<view>
		<cmd-nav-bar back title="登录" rightText="注册" @rightText="fnRegisterWin"></cmd-nav-bar>
		<cmd-page-body type="top">
			<!-- #ifdef H5 || APP-PLUS -->
		    <view class="login">
				<!-- 上部分 start -->
				<view class="login-title">{{ status ? '手机快捷登录': '使用账号密码登录'}}</view>
				<!-- 上部分 end -->
				<!-- 手机验证码登录 start -->
				<cmd-transition name="fade-up">
					<view v-if="status">
						<view class="login-phone">
						  <cmd-input v-model="mobile.phone" type="number" focus maxlength="11" placeholder="请输入手机号"></cmd-input>
						  <view class="login-phone-getcode" @tap="!safety.state ? fnGetPhoneCode() : ''">{{!safety.state&&'获取验证码'||(safety.time+' s')}}</view>
						</view>
						<view class="login-code">
						  <cmd-input v-model="mobile.code" type="number" maxlength="6" placeholder="请输入短信验证码"></cmd-input>
						</view>
						<button class="btn-login" :class="loginMobile ? 'btn-login-active':''" :disabled="!loginMobile" hover-class="btn-login-hover"
						  @tap="fnLogin">登录</button>
					</view>
				</cmd-transition>
				<!-- 手机验证码登录 end -->
				<!-- 手机密码登录 start -->
				<cmd-transition name="fade-up">
					<view v-if="!status">
						<view class="login-username">
						  <cmd-input v-model="account.username" type="text" focus maxlength="26" placeholder="请输入账号"></cmd-input>
						</view>
						<view class="login-password">
						  <cmd-input v-model="account.password" type="password" displayable maxlength="26" placeholder="请输入密码"></cmd-input>
						</view>
						<button class="btn-login" :class="loginAccount ? 'btn-login-active':''" :disabled="!loginAccount"
						  hover-class="btn-login-hover" @tap="fnLogin">登录</button>
					</view>
				</cmd-transition>
				<!-- 手机密码登录 end -->
				<!-- 切换登录方式 -->
				<view class="login-mode" @tap="fnChangeStatus(false)">{{status ?	'账号密码登录' : '手机快捷登录'}}</view>
			</view>
			<!-- #endif -->
			<!-- #ifdef MP-WEIXIN -->
			<!-- 微信小程序登录 -->
			<view class="mp-wx">
				<text class="login-desc">申请获得你的公开信息（昵称、头像等）</text>
				<button class="login-btn" type="primary" @tap="getUserInfo">
					<view class="item column center">
						微信一键授权
					</view>
				</button>
			</view>
			<!-- #endif -->
		</cmd-page-body>
	</view>
</template>

<script>
	import cmdNavBar from "@/components/cmd-nav-bar/cmd-nav-bar.vue"
	import cmdPageBody from "@/components/cmd-page-body/cmd-page-body.vue"
	import cmdTransition from "@/components/cmd-transition/cmd-transition.vue"
	import {mpWxAuth, mobileCode, mobileAuth, passwordAuth} from '@/common/api'
	import md5 from '@/common/md5'
	export default {
		components:{
		    cmdNavBar,
			cmdPageBody,
			cmdTransition,
		},
		data() {
			return {
				// 账号登录部分数据
				account: {
				  username: '',
				  password: ''
				},
				usernameReg: /^[A-Za-z0-9]+$/,
				passwordReg: /^\w+$/,
				loginAccount: false,
				// 手机登录部分数据
				mobile: {
				  phone: '',
				  code: ''
				},
				// 验证码
				safety: {
				  time: 60,
				  state: false,
				  interval: ''
				},
				loginMobile: false,
				phoneReg: /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/,
				status: true // true手机登录,false账号登录
			};
		},
		watch: {
		  /**
		   * 监听手机登录数值
		   */
		  mobile: {
		    handler(newValue) {
		      if (this.phoneReg.test(newValue.phone) && newValue.code.length >= 1) {
		        this.loginMobile = true;
		      } else {
		        this.loginMobile = false;
		      }
		    },
		    deep: true
		  },
		  /**
		   * 监听账号登录数值
		   */
		  account: {
		    handler(newValue) {
		      if ((this.usernameReg.test(newValue.username) && newValue.username.length >= 1) && (this.passwordReg.test(
		          newValue.password) && newValue.password.length >= 1)) {
		        this.loginAccount = true;
		      } else {
		        this.loginAccount = false
		      }
		    },
		    deep: true
		  }
		},
		onLoad(object) {},
		methods: {
			/**
			 * 设置用户资料
			 */
			getUserInfo() {
				wx.getUserProfile({
				  desc: '用于完善用户资料',
				  success: (res) => {
					this.wxLogin(res.userInfo);
				  },
				  fail: (res) => {
				  	uni.showToast({
				  		title: "授权失败",
				  		icon:'exception',
				  		duration:850
				  	});
				  }
				})
			},
			/**
			 * 微信登录
			 */
			wxLogin(params) {
				uni.login({
				     provider: 'weixin',
				     success: (res) => {
						this.code = res.code;
				        if (res.errMsg == 'login:ok') {
							params.code = res.code;
							mpWxAuth(params).then(res => {
								uni.showToast({
									title: res.message,
									icon:'exception',
									duration:850
								});
								if (res.code == 200) {
									uni.setStorageSync('token',res.data.token);
									uni.setStorageSync('sessionKey',res.data.sessionKey);
									getApp().getUserInfo(function () {
										uni.switchTab({
										    url: '/pages/tabBar/index/index',
										})
									});
								} 
							})
						}
					}
				})
			},
			/**
			 * 获取验证码
			 */
			fnGetPhoneCode() {
			  if (this.phoneReg.test(this.mobile.phone)) {
			    uni.showToast({
			      title: "正在发送验证码",
			      icon: "loading",
			      success: () => {
			        // 成功后显示倒计时60s后可在点击
			        this.safety.state = true;
			        // 倒计时
			        this.safety.interval = setInterval(() => {
			          if (this.safety.time-- <= 0) {
			            this.safety.time = 60;
			            this.safety.state = false;
			            clearInterval(this.safety.interval);
			          }
			        }, 1000);
					let params = {
						mobile: this.mobile.phone
					}
					mobileCode(params).then(res => {
						uni.showToast({
						  title: "发送成功",
						  icon: "success"
						})
					});
			      }
			    })
			  } else {
			    uni.showToast({
			      title: "手机号不正确",
			      icon: "none"
			    })
			  }
			},
			/**
			 * 登录按钮点击执行
			 */
			fnLogin() {
				if (this.status) {
				  // 手机号验证码登录
				  let params = {
				  	mobile: this.mobile.phone,
				  	code: this.mobile.code
				  }
				  mobileAuth(params).then(res => {
				  	uni.showToast({
				  		title: res.message,
				  		icon:'exception',
				  		duration:850
				  	});
					if (res.code == 200) {
				  		uni.setStorageSync('token',res.data.token);
				  		getApp().getUserInfo(function () {
				  			uni.switchTab({
				  				url: '/pages/tabBar/index/index',
				  			})
				  		});			
				  	}
				  });
				} else {
				  let params = {
					mobile: this.account.username,
					appSecret: md5(this.account.password)
				  }
				  // 账号、密码登录
				  passwordAuth(params).then(res => {
					  uni.showToast({
					  	title: res.message,
					  	icon:'exception',
					  	duration:850
					  });
					  if (res.code == 200) {
					  	uni.setStorageSync('token',res.data.token);
					  	getApp().getUserInfo(function () {
					  		uni.switchTab({
					  			url: '/pages/tabBar/index/index',
					  		})
					  	});			
					  }
				  });
				}
			},
			/**
			 * 改变登录方式状态 reset作为重置标识
			 */
			fnChangeStatus(reset) {
			  // 手机登录部分
			  this.mobile = {
			    phone: '',
			    code: ''
			  }
			  this.loginMobile = false
			  // 账号登录部分
			  this.account = {
			    username: '',
			    password: ''
			  }
			  this.loginAccount = false
			  // 验证码时间状态还原
			  clearInterval(this.safety.interval);
			  this.safety.time = 60;
			  this.safety.state = false;
			  if (!reset) {
			    // 可以延迟3毫秒后切换
			    this.status = !this.status;
			  }
			},
			/**
			 * 跳转注册页面
			 */
			fnRegisterWin() {
			  uni.navigateTo({
			    url: "/pages/user/register/register"
			  })
			  /**
			   * 改变状态重置，跳转不会摧毁实例
			   */
			  this.fnChangeStatus(true);
			}
		},
		beforeDestroy() {
		  /**
		   * 关闭页面清除轮询器
		   */
		  clearInterval(this.safety.interval);
		}
	}
</script>

<style scoped lang='scss'>
	.mp-wx {
	  display: flex;
	  flex-direction: column;
	  align-items: center;
	  padding-top: 25%;
	  .login-desc {
	      color: #999;
	      font-size: 14px;
	      margin-top: 16px;
	  }
	  .login-btn {
	      margin-top: 16px;
	      width: 85%;
	  }
	}
	.login {
	  margin-top: 56upx;
	  margin-right: 72upx;
	  margin-left: 72upx;
	}
	
	.login-title {
	  font-size: 56upx;
	  font-weight: 500;
	}
	
	.login-explain {
	  font-size: 28upx;
	  color: #9E9E9E;
	}
	
	.login-phone {
	  display: flex;
	  flex-direction: row;
	  justify-content: space-between;
	  align-items: center;
	  border-bottom: 2upx #dedede solid;
	  margin-top: 56upx;
	  margin-bottom: 40upx;
	}
	
	.login-phone-getcode {
	  color: #3F51B5;
	  text-align: center;
	  min-width: 140upx;
	}
	
	.login-code {
	  border-bottom: 2upx #dedede solid;
	}
	
	.login-username {
	  margin-top: 56upx;
	  margin-bottom: 40upx;
	  border-bottom: 2upx #dedede solid;
	}
	
	.login-password {
	  border-bottom: 2upx #dedede solid;
	}
	
	.btn-login {
	  margin-top: 100upx;
	  border-radius: 50upx;
	  font-size: 16px;
	  color: #fff;
	  background: linear-gradient(to right, #88a1f9, #9ac6ff);
	}
	
	.btn-login-active {
	  background: linear-gradient(to right, #365fff, #36bbff);
	}
	
	.btn-login-hover {
	  background: linear-gradient(to right, #365fdd, #36bbfa);
	}
	
	button[disabled] {
	  color: #fff;
	}
	
	.login-mode {
	  text-align: center;
	  margin-top: 32upx;
	}
</style>